const Web3 = require('web3')

if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
}


var chapter = require('../build/contracts/Chapter.json')
var head = require('../build/contracts/Head.json')

var CTR_chapter = new web3.eth.Contract(chapter.abi)
var CTR_Head = new web3.eth.Contract(head.abi)


function deployChapter(){
    return Promise((resolve,reject)=>{
        CTR_chapter.deploy({
            data:chapter.bytecode,
            arguments: ["miracle","0xdc20034c256d04a3e16d58d450d48b159e043e39", "0xdc20034c256d04a3e16d58d450d48b159e043e39", "0xdc20034c256d04a3e16d58d450d48b159e043e39", "I'm text", 0]
        }).send({
            from: '0xd42F15E027aE2F86bD05De4357fB282c561115c3',
            gas: 1500000,
            gasPrice: '30000000000000'
        },(error, transactionHash) => { 
            if(error){
                console.log("error")
                reject(error)
            }else{
                console.log("deploy success", transactionHash)
                resolve(transactionHash)
            }
        })
    })
}
function addToHead({title,address,prev}){
    CRT_head.methods.addNode(title,address,prev).call().then((flag) => {
        console.log(flag)
    });
}
function addChapter(){
    var title = "获得秘籍"
    var auther = "0xdc20034c256d04a3e16d58d450d48b159e043e39"
    var owner = "0xdc20034c256d04a3e16d58d450d48b159e043e39"
    var prev = "0xdc20034c256d04a3e16d58d450d48b159e043e39"
    var text = "I'm text"
    var star = 0

    deployChapter(title,auther,owner,prev,text,star).then((chapterAddress)=>{
        addToHead({title,address:chapterAddress,prev})
    })

}
